package cn.edu.wfit.modules.directionmanagement.controller;

import cn.edu.wfit.modules.directionmanagement.domain.CodeExecutionRequest;
import cn.edu.wfit.modules.directionmanagement.domain.CodeExecutionResponse;
import cn.edu.wfit.modules.directionmanagement.service.OnlineIdeService;
import cn.edu.wfit.modules.directionmanagement.util.CodeSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 在线IDE控制器
 */
@RestController
@RequestMapping("/api/online-ide")
public class OnlineIdeController {

    @Autowired
    private OnlineIdeService onlineIdeService;

    /**
     * 执行代码
     */
    @PostMapping("/execute")
    public CodeExecutionResponse executeCode(@RequestBody CodeExecutionRequest request) {
        // 安全检查
        if (!isCodeSafe(request)) {
            CodeExecutionResponse response = new CodeExecutionResponse();
            response.setSuccess(false);
            response.setError("代码包含危险操作，执行被拒绝");
            return response;
        }
        
        return onlineIdeService.executeCode(request);
    }
    
    /**
     * 检查代码是否安全
     * @param request 代码执行请求
     * @return 是否安全
     */
    private boolean isCodeSafe(CodeExecutionRequest request) {
        switch (request.getLanguage().toLowerCase()) {
            case "java":
                return CodeSecurityUtil.isJavaCodeSafe(request.getSourceCode());
            case "python":
                return CodeSecurityUtil.isPythonCodeSafe(request.getSourceCode());
            case "cpp":
                return CodeSecurityUtil.isCppCodeSafe(request.getSourceCode());
            default:
                return false;
        }
    }
}